package com.pes.arcww.dao;

import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.pes.arcww.form.Topics;

@Repository
public class TopicsDAOImpl implements TopicsDAO{

	@Autowired
	private SessionFactory sessionFactory;
	
	public void addTopic(Topics topic) {
		sessionFactory.getCurrentSession().save(topic);
	}

	@SuppressWarnings("unchecked")
	public Collection<Topics> listTopics(String filter, String value) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Topics.class);
		
		if(filter.equals("") && value.equals("")){
			criteria.addOrder(Order.desc("top_id"));
		}else if(filter.equals("id")){
			criteria.add(Restrictions.sqlRestriction(" top_id LIKE '%"+value+"%' ")).addOrder(Order.desc("top_id"));
		}else if(filter.equals("title")){
			criteria.add(Restrictions.like("title", "%"+value+"%")).addOrder(Order.asc("title"));
		}else{//description
			criteria.add(Restrictions.like("description", "%"+value+"%")).addOrder(Order.asc("description"));
		}

		return criteria.list();
		
	}

	public void removeTopic(Integer id) {
		Topics topic = getTopic(id);
		if(topic != null){
			sessionFactory.getCurrentSession().delete(topic);
		}
	}

	public void updateTopic(Topics topic) {
		sessionFactory.getCurrentSession().update(topic);
	}

	public Topics getTopic(Integer id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Topics topic = (Topics) session.get(Topics.class, id);
		Hibernate.initialize(topic.getQuestionsList()); 
		session.getTransaction().commit();
		session.close();
		
		return topic;
	}
}
